######################################################################
# Time-stamp: <04/09/23 14:43:24 ostolop>
######################################################################
package EP::EPC::Core::Sequence_Homology;

use strict;

use EP::Config;
use EP::Common;
use EP::Common::General;

use EP::EPC::Core;
use EP::EPC::Core::Component;

use CGI qw/:standard/;

use Carp;
use Carp qw (cluck);

use Bio::Tools::Run::RemoteBlast;

our @ISA = qw ( EP::EPC::Core::Component );

sub process_component {
  my $self = shift;

  my $result = $self->_run_BlastN ( $self->{src_dataset} ) if $self->{query}->param( "program" ) eq 'blastn';
  my $process_result = { html => $result }; # HACK: produce HTML output and place it all directly in <html></html> as a result!

  $self->{CD}->{process_result} = $process_result;
  return OK;
}

sub _run_BlastN {
  my $self = shift;
  my ($src_dataset) = @_;

  my $file = $EP::Config::h->{EPNG_USRDATA_PATH} . "/" . $src_dataset->folder->location . "/" . $src_dataset->filename . ".fasta";

  my $prog = 'blastn';
  my $db   = 'swissprot';
  my $e_val= '1e-10';

  my $HTML_OUTPUT = start_html( -title => "GO",
				-target => "_blank",
				-bgcolor => "white"
			      );

  my @params = ( '-prog' => $prog,
		 '-data' => $db,
		 '-expect' => $e_val,
		 '-readmethod' => 'SearchIO' );

  my $factory = Bio::Tools::Run::RemoteBlast->new(@params);

  my $r = $factory->submit_blast($file);
  my $v = 1;
  warn "waiting..." if( $v > 0 );
  while ( my @rids = $factory->each_rid ) {
    foreach my $rid ( @rids ) {
      my $rc = $factory->retrieve_blast($rid);
      if( !ref($rc) ) {
	if( $rc < 0 ) {
	  $factory->remove_rid($rid);
	}
	warn "." if ( $v > 0 );
	sleep 5;
      } else {
	my $result = $rc->next_result();
	#save the output
	#          my $filename = $result->query_name()."\.out";
	#          $factory->save_output($filename);
	$factory->remove_rid($rid);
	$HTML_OUTPUT .= "\nQuery Name: ". $result->query_name(). "\n";
	while ( my $hit = $result->next_hit ) {
	  next unless ( $v > 0);
	  $HTML_OUTPUT .= "\thit name is ". $hit->name. "\n";
	  while( my $hsp = $hit->next_hsp ) {
	    $HTML_OUTPUT .= "\t\tscore is ". $hsp->score. "\n";
	  }
	}
      }
    }
  }
  $HTML_OUTPUT .= end_html();

  return $HTML_OUTPUT;
  #    return "<body><p>Something went wrong here</p></body>";
}
